package cpe.hapa.dao;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.servlet.http.HttpServletRequest;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.SortDirection;

import cpe.hapa.authentication.Authenticate;
import cpe.hapa.model.Vol;

public class SearchDAO {

	public static Key addSearch(String leaving, String goingTo, Date departure, int responseCount, String key)
	{
		DatastoreService datastore = DatastoreSingleton.getInstance();		
		
		Entity newSearch = new Entity("Search");
		newSearch.setProperty("date", new Date());
		newSearch.setProperty("leavingFrom", leaving);
		newSearch.setProperty("goingTo", goingTo);
		newSearch.setProperty("departure", departure);
		newSearch.setProperty("responseCount", responseCount);
		newSearch.setProperty("user", key);		
		
		return datastore.put(newSearch);
	}

	public static void updateSearch(Key searchKey) throws EntityNotFoundException, CacheException {
		DatastoreService datastore = DatastoreSingleton.getInstance();	
		Cache cache = DatacacheSingleton.getInstance();
		Entity search = datastore.get(searchKey);
		cache.put("departure", search.getProperty("departure"));
		cache.put("goingTo", search.getProperty("goingTo"));
		cache.put("leavingFrom", search.getProperty("leavingFrom"));
		search.setProperty("date", new Date());
		datastore.put(search);
	}
	
	public static PreparedQuery getHistoric(HttpServletRequest request) throws NumberFormatException, ParseException{
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Filter userFilter = new FilterPredicate("user", FilterOperator.EQUAL, KeyFactory.keyToString(Authenticate.getConnectedUser(request).getKey()));
		Query researchListQuery = new Query("Search")
		.setFilter(userFilter)
		.addSort("date", SortDirection.ASCENDING);
		
		return datastore.prepare(researchListQuery);
	}
}
